<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>需求工单信息</span>
        <el-row style="float: right">
          <el-button :disabled="detail.service_count === 100000" @click="TapdDialogVisible">Tapd导入</el-button>
          <el-button @click="addRowVisible">补单</el-button>
        </el-row>
      </div>
      <el-descriptions direction="vertical" :column="4" border>
        <el-descriptions-item label="业务线">{{ detail.business_name }}</el-descriptions-item>
        <el-descriptions-item label="环境">{{ detail.env_name }}</el-descriptions-item>
        <el-descriptions-item label="服务数">{{ detail.service_count }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detail.status }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detail.comment }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>流程信息</span>
      </div>
      <el-steps :active="active" finish-status="success">
        <el-step v-for="item in stepData.steps" :key="item.step" :title="item.step_name" :description="item.opuser" />
      </el-steps>

      <!-- <el-button style="margin-top: 12px;" @click="next">下一步</el-button> -->
      <el-button v-for="item in stepData.buttons" :key="item.name" :disabled="item.disable" @click="next(item)">{{ item.name }}</el-button>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>工单信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="fetchWorkOrder()">刷新</el-button>
      </div>
      <el-table
        :data="workorderlist"
        border
      >
        <el-table-column

          prop="id"
          label="编号"
          width="50"
        />
        <el-table-column

          prop="service_name"
          label="服务名"
        />

        <el-table-column
          prop="version"
          label="发布版本"
          width="250"
        />
        <el-table-column
          prop="cur_deployment_info.imagetag"
          label="当前版本"
          width="250"
        />
        <el-table-column
          prop="cur_deployment_info.status"
          label="容器副本"
          :render-header="handleRenderHeader"
        />
        <el-table-column
          prop="status"
          label="工单状态"
          width="100"
        />
        <el-table-column
          prop="cur_step_name"
          label="当前步骤"
        />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <router-link :to="{ name: 'DeployDetail', query: { id: scope.row.id }}">详情</router-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :visible.sync="dialogFormVisible" title="">

      <el-table
        :data="form.services"
        border
      >
        <el-table-column

          label="编号"
          width="50"
          type="index"
        />
        <el-table-column

          prop="name"
          label="服务名"
        />
        <el-table-column

          prop="version"
          label="版本"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeService(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <el-form ref="dynamicValidateForm" :model="form.select" :inline="true" label-width="100px" class="demo-dynamic">
        <el-form-item
          label="服务"
          prop="name"
          :rules="[
            { required: true, message: '服务不能为空' }
          ]"
        >
          <el-select v-model="form.select.name" filterable placeholder="请选择" @change="serviceChangeHandle">
            <el-option
              v-for="item in serviceData"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="版本"
          prop="version"
          :rules="[
            { required: true, message: '版本不能为空' }
          ]"
        >
          <el-select v-model="form.select.version" filterable placeholder="请选择">
            <el-option
              v-for="item in tagData"
              :key="item.Tag"
              :label="item.Tag"
              :value="item.Tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click.prevent="addService('dynamicValidateForm')">添加</el-button>
        </el-form-item>
        <el-divider />
        <el-form-item style="float: right">
          <el-button type="primary" @click="addWorkOrderHandle">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- Tapd 导入-->
    <div>
      <el-dialog :visible.sync="TapdDialogFormVisible" title="Tapd导入">
        <el-row>
          <el-steps :active="tapdactive" finish-status="success" align-center>
            <el-step title="从Tapd导入" />
            <el-step title="确认镜像" />
          </el-steps>
        </el-row>
        <el-divider />
        <el-row>
          <el-form :inline="true" :model="tapdform" class="demo-form-inline">
            <div v-if="tapdactive===1" class="info">
              <el-form-item label="项目空间">
                <el-select v-model="tapdform.tapd.workspace_id" filterable placeholder="请选择">
                  <el-option
                    v-for="item in tapdData.workspaces"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="上线时间">
                <el-date-picker
                  v-model="tapdform.tapd.deploy_date"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="tapdform.tapd.status" multiple placeholder="请选择">
                  <el-option
                    v-for="item in tapdData.statuslist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div v-if="tapdactive===2" class="info">
              <el-table
                v-loading="tapdloading"
                :data="tapdform.orders"
                border
              >
                <el-table-column

                  label="编号"
                  width="50"
                  type="index"
                />
                <el-table-column

                  prop="name"
                  label="服务名"
                />
                <el-table-column

                  prop="version"
                  label="版本"
                />
                <el-table-column fixed="right" label="操作" width="220">
                  <template #default="scope">
                    <el-button type="danger" size="small" @click="removeTapdService(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

            </div>
            <el-divider />
            <el-form-item style="float: right">
              <el-button v-if="tapdactive>1" type="primary" @click="tapdPre">上一步</el-button>
              <el-button v-if="tapdactive<2" type="primary" @click="tapdNext">下一步</el-button>
              <el-button v-if="tapdactive===2" type="primary" @click="tapdSubmit">提交</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-dialog>
    </div>

  </div>

</template>
<script>
import { getDetail, getWorkOrder, getSteps, doStep, addWorkOrders, getServiceList, getImageTagList, getLatestImageTag } from '@/api/flow/multideploy'
import { getWorkspaces, getServices } from '@/api/eff/tapd'
import moment from 'moment'
export default {
  data() {
    return {
      // step定时器
      steptimer: 0,
      detail: {},
      active: 0,
      current_opuser: '',
      current_step: '',
      status: 'wait',
      demandorder: this.$route.query.id,
      workorderlist: [],
      stepData: {
        steps: [],
        buttons: []
      },
      form: {
        services: [],
        select: { id: '', name: '', version: '' }
      },
      dialogFormVisible: false,
      serviceData: [],
      tagData: [],
      // tapd
      TapdDialogFormVisible: false,
      tapdactive: 1,
      tapdform: {
        tapd: {
          workspace_id: '',
          deploy_date: '',
          status: ''
        },
        orders: []
      },
      tapdloading: true,
      tapdData: {
        statuslist: [
          { 'label': '待开发', 'value': 'audited' },
          { 'label': '待测试', 'value': 'status_9' },
          { 'label': '测试中', 'value': 'product_experience' },
          { 'label': '已上线', 'value': 'resolved' },
          { 'label': '开发中', 'value': 'developing' },
          { 'label': '待评审', 'value': 'auditing' }
        ],
        workspaces: [],
        services: []
      }
    }
  },

  created() {
    this.fetchData()
    this.steptimer = setInterval(this.checkAuto, 10000)
  },
  beforeDestroy() {
    clearInterval(this.steptimer)
  },
  methods: {
    flushSteps() {
      this.stepData.steps = []
      this.stepData.buttons = []
    },
    fetchData() {
      this.fetchDetail()
      this.fetchWorkOrder()
      this.fetchSteps()
    },

    fetchDetail() {
      getDetail({ id: this.demandorder }).then(response => {
        this.detail = response
      })
    },
    fetchWorkOrder() {
      getWorkOrder({ demand: this.demandorder, page_size: 100 }).then(response => {
        this.workorderlist = response.data
      })
    },
    fetchSteps() {
      this.flushSteps()
      getSteps({ id: this.demandorder }).then(response => {
        this.stepData.steps = response.data.steps
        this.stepData.buttons = response.data.buttons
        this.active = response.active
        this.status = response.status
        this.current_opuser = response.current_opuser
        this.current_step = response.current_step
        // this.watchStep()
        // this.checkAuto()
      })
    },
    fetchServices() {
      getServiceList({ business: this.detail.business_id, page_size: 100, order_by: 'code' }).then(response => {
        this.serviceData = response.data
      })
    },
    serviceChangeHandle() {
      getImageTagList({ id: this.demandorder, service_name: this.form.select.name }).then(response => {
        this.tagData = response.data
      })
    },
    watchStep() {
      console.log(this.active, this.status)
      if (this.current_opuser === 'auto' & this.status === 'wait') {
        // console.log('watch', this.steptimer)
        // if (this.steptimer === 0) {
        //   this.steptimer = window.setInterval(this.checkAuto(), 10000)
        // }
        // setTimeout(this.checkAuto, 10000)
      } else {
        // window.clearInterval(this.steptimer)
        console.log('clear watch123', this.steptimer)
      }
    },
    checkAuto() {
      console.log(this.current_opuser, this.status, 'run')
      if (this.current_opuser === 'auto' & this.status === 'wait') {
        doStep({ 'id': this.demandorder, 'step': this.current_step, 'action': 'yes' }).then(
          response => {
            if (response.code === 20000 & response.status === 'finish') {
              setTimeout(() => {
                this.fetchSteps()
                this.fetchWorkOrder()
              }, 5000)
            }
          }
        )
      } else if (this.status === 'finish' || this.status === 'cancel') {
        this.fetchWorkOrder()
        this.fetchDetail()
        clearInterval(this.steptimer)
        this.steptimer = 0
        setTimeout(console.log(this.status, this.steptimer), 3000)
      }
    },
    next(item) {
      console.log(item)

      doStep({ 'id': this.demandorder, 'step': item.step_function, 'action': item.action }).then(
        response => {
          this.fetchSteps()
        }
      )
    },
    handleRenderHeader(h, { column, $index }) {
      return h('el-tooltip', {
        props: {
          content: (function() {
            return '可用副本/副本数'
          })(),
          placement: 'top'
        },
        domProps: {
          innerHTML: column.label + '<span class="el-icon-question"></span>'
        }
      },
      [h('span')])
    },
    // 新增服务
    addRowVisible() {
      // 解决form缓存问题
    //   this.form = {}
      this.fetchServices()
      this.dialogFormVisible = true
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    removeService(item) {
      var index = this.form.services.indexOf(item)
      if (index !== -1) {
        this.form.services.splice(index, 1)
      }
    },
    addService(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.services.push({ name: this.form.select.name, version: this.form.select.version })
          this.form.select = { name: '', version: '' }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addWorkOrderHandle() {
      this.dialogFormVisible = false

      addWorkOrders({ services: this.form.services, id: this.demandorder }).then(response => {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.fetchWorkOrder()
        this.fetchSteps()
        this.form.services = []
        if (this.steptimer === 0) {
          this.steptimer = setInterval(this.checkAuto, 10000)
        }
      })
    },
    // tapd
    TapdDialogVisible() {
      this.fetchTapdWorkspace()
      this.initDate()
      this.TapdDialogFormVisible = true
    },
    fetchTapdWorkspace() {
      getWorkspaces().then(response => {
        this.tapdData.workspaces = response.data
        this.tapdform.tapd.workspace_id = response.data[0].id
      })
    },
    fetchTapdServices() {
      this.tapdform.orders = []
      this.tapdloading = true
      getServices(this.tapdform.tapd).then(response => {
        const data = response.data
        for (const service of data.pipeline) {
          getLatestImageTag({ id: this.demandorder, service_name: service }).then(response => {
            const version = response.imagetag
            this.tapdform.orders.push({ name: service, version: version })
          }).catch(err => {
            console.error(err)
            this.tapdform.orders.push({ name: service, version: '' })
          })
        }
        this.tapdloading = false
        // this.blacklist = data.blacklist.join('\n')
        // this.dialogVisible = true
        console.log(this.tapdData.services)
      })
    },
    initDate() {
      const day = new Date()
      const weekday = day.getDay()
      if (weekday === 1 || weekday === 2) {
        day.setDate(day.getDate() - weekday + 2)
      } else {
        day.setDate(day.getDate() - weekday + 4)
      }
      this.tapdform.tapd.deploy_date = moment(day).format('YYYY-MM-DD')
    },
    tapdPre() {
      this.tapdactive -= 1
    },
    tapdNext() {
      if (this.tapdactive === 1) {
        console.log(this.tapdactive)
        this.fetchTapdServices()
      }
      this.tapdactive += 1
    },
    removeTapdService(item) {
      var index = this.tapdform.orders.indexOf(item)
      if (index !== -1) {
        this.tapdform.orders.splice(index, 1)
      }
    },
    tapdSubmit() {
      console.log(this.tapdactive)
      addWorkOrders({ services: this.tapdform.orders, id: this.demandorder, src: 'tapd' }).then(response => {
        if (response.errService.length !== 0) {
          this.$message({
            type: 'warning',
            message: response.msg
          })
        } else {
          this.$message({
            type: 'success',
            message: response.msg
          })
        }

        this.fetchData()
        this.TapdDialogFormVisible = false
      })
    }
  }
}
</script>

<style>

</style>
